<template>
  <div class="myVideo">
    <video class="myVideo" ref="videoEle" controls muted width="600"></video>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted ,reactive } from 'vue';
import Hls from 'hls.js';

// 接收父组件传递的视频 URL
const props = defineProps({
  url: {
    type: String,
    default: '',
  },
});

// 使用 ref 获取视频元素
const videoEle = ref(null);
let hlsInstance = null;
let autoPlayTimer = null;

// 初始化播放器
const initializePlayer = () => {
  if (!props.url) {
    console.log('正在加载视频...');
    return;
  }
  hlsPlay();
};

// 使用 HLS.js 播放视频
const hlsPlay = () => {
  if (Hls.isSupported()) {
    hlsInstance = new Hls();
    hlsInstance.loadSource(props.url);
    hlsInstance.attachMedia(videoEle.value);
    hlsInstance.on(Hls.Events.BUFFERING, () => {
      console.log('缓冲中...');
    });
    hlsInstance.on(Hls.Events.MANIFEST_PARSED, () => {
      autoPlay();
    });
  } else if (videoEle.value.canPlayType('application/vnd.apple.mpegurl')) {
    videoEle.value.src = props.url;
    videoEle.value.addEventListener('canplay', autoPlay);
  }
};

// 自动播放逻辑
const autoPlay = () => {
  clearTimeout(autoPlayTimer);
  autoPlayTimer = setTimeout(() => {
    if (videoEle.value && !videoEle.value.paused) {
      videoEle.value.play();
    }
  }, 500);
};

// 监听 URL prop 的变化
watch(() => props.url, (newVal) => {
  if (newVal) {
    initializePlayer();
  }
}, { immediate: true });

// 组件挂载后初始化播放器
onMounted(() => {
  initializePlayer();
});

// 组件卸载前清理资源
onUnmounted(() => {
  if (hlsInstance) {
    hlsInstance.destroy();
  }
  clearTimeout(autoPlayTimer);
});
</script>

<style scoped>
.myVideo {
  width: 100%;
  height: auto; /* 根据需要调整高度 */
}
</style>